import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const request = axios.create({
    baseURL: 'http://192.168.0.139:2000/apis/',
    timeout: 15000
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 可以在这里添加token等认证信息
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers['Authorization'] = `Bearer ${userStore.token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
            ElMessage({
                message: res.message || '错误',
                type: 'error',
                duration: 5 * 1000
            })

            if (res.code === 401 || (res.code === 500 && res.message === '暂未登录或token已经过期')) {
                // token过期处理
                useRouter().push('/login')
            }
            return Promise.reject(new Error(res.message || '错误'))
        }
        return res
    },
    error => {
        ElMessage({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default request
